package com.cskaoyan.app.wxservice.impl;

import com.cskaoyan.app.bean.bo.CommentBO;
import com.cskaoyan.app.bean.bo.OrderIDBO;
import com.cskaoyan.app.bean.bo.SubmitBO;
import com.cskaoyan.app.bean.common.CommonData;
import com.cskaoyan.app.bean.po.*;
import com.cskaoyan.app.bean.vo.orderVo.WeChatOrderDetailVO;
import com.cskaoyan.app.bean.vo.orderVo.WeChatOrderListGoods;
import com.cskaoyan.app.bean.vo.orderVo.WeChatOrderListHandleOption;
import com.cskaoyan.app.bean.vo.orderVo.WeChatOrderListVO;
import com.cskaoyan.app.mapper.*;
import com.cskaoyan.app.wxcontroller.WeChatOrderController;
import com.cskaoyan.app.wxservice.WeChatOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Shuuka
 * @email 1712430536@qq.com
 * @date 2022/12/31 22:22
 */
@Service
@Transactional
public class WeChatOrderServiceImpl implements WeChatOrderService {

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Override
    public CommonData<WeChatOrderListVO> list(Integer showType, Integer page, Integer limit, Integer userid) {
        PageHelper.startPage(page, limit);
        List<WeChatOrderListVO> weChatOrderListVOList = marketOrderMapper.listWeChat(showType, userid);
        for (WeChatOrderListVO weChatOrderListVO : weChatOrderListVOList) {
            weChatOrderListVO.setOrderStatusText(setStatusText(weChatOrderListVO.getOrderStatus()));
            weChatOrderListVO.setHandleOption(setHandleOption(weChatOrderListVO.getComments(), weChatOrderListVO.getOrderStatus(), weChatOrderListVO.getOrderDeleted()));
            weChatOrderListVO.setIsGroupin(false);
            if (!weChatOrderListVO.getGrouponPrice().toString().equals("0.00")) {
                weChatOrderListVO.setIsGroupin(true);
            }
        }
        PageInfo<WeChatOrderListVO> pageInfo = new PageInfo<>(weChatOrderListVOList);
        return CommonData.data(pageInfo);
    }

    @Override
    public WeChatOrderDetailVO detail(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);

        String shipChannel = marketOrder.getShipChannel();
        String shipSn = marketOrder.getShipSn();
        marketOrder.setExpNo(shipSn);
        marketOrder.setExpCode(shipChannel);
        String expName = marketOrderMapper.ship(shipChannel);
        marketOrder.setExpName(expName);

        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        WeChatOrderDetailVO weChatOrderDetailVO = new WeChatOrderDetailVO();
        marketOrder.setHandleOption(setHandleOption(marketOrder.getComments(), marketOrder.getOrderStatus(), marketOrder.getDeleted()));
        weChatOrderDetailVO.setOrderInfo(marketOrder);
        weChatOrderDetailVO.setOrderGoods(marketOrderGoods);
        return weChatOrderDetailVO;
    }

    @Override
    public Integer refund(Integer orderId) {
        Integer row = marketOrderMapper.updateRefund(orderId);
        return row;
    }

    @Override
    public Integer confirm(Integer orderId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        short size = (short) marketOrderGoods.size();
        Integer row = marketOrderMapper.updateConfirm(orderId, size);
        return row;
    }

    @Override
    public Integer delete(Integer orderId) {
        Integer row = marketOrderMapper.deleteByPrimaryKey(orderId);
        return row;
    }

    @Override
    public MarketOrderGoods goods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andGoodsIdEqualTo(goodsId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        if (marketOrderGoods.size() == 1) {
            return marketOrderGoods.get(0);
        }
        return null;
    }

    @Override

    public Integer comment(CommentBO commentBO, Integer userid) {
        //从订单商品表查询订单id和商品id
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByPrimaryKey(commentBO.getOrderGoodsId());
        Integer goodsId = marketOrderGoods.getGoodsId();
        Integer orderId = marketOrderGoods.getOrderId();

        MarketComment marketComment = new MarketComment();
        marketComment.setUserId(userid);
        marketComment.setStar(commentBO.getStar());
        marketComment.setContent(commentBO.getContent());
        marketComment.setHasPicture(commentBO.getHasPicture());
        marketComment.setValueId(goodsId);
        marketComment.setPicUrls(commentBO.getPicUrls());
        marketComment.setType((byte) 0);
        Date now = new Date();
        marketComment.setAddTime(now);
        marketComment.setUpdateTime(now);
        Integer rowA = marketCommentMapper.insertSelective(marketComment);
        marketOrderGoods.setUpdateTime(now);
        marketOrderGoods.setComment(marketComment.getId());

        Integer rowB = marketOrderGoodsMapper.updateByPrimaryKeySelective(marketOrderGoods);
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        short comments = marketOrder.getComments();
        marketOrder.setId(orderId);
        marketOrder.setUpdateTime(now);
        if (comments > 0) {
            marketOrder.setComments((short) (comments - 1));
        }
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        return rowA + rowB;
    }

    @Override
    public Integer submit(SubmitBO submitBO, Integer userid) {
        //1.发货地址信息
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(submitBO.getAddressId());
        //2.购物车商品信息
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userid);
        if (submitBO.getCartId() != 0) {
            criteria.andIdEqualTo(submitBO.getCartId());
        }
        criteria.andDeletedEqualTo(false);
        criteria.andCheckedEqualTo(true);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        if(marketCarts == null || marketCarts.size() ==0 ){
            return 400;
        }
        //3.用户优惠券信息
        BigDecimal zero = new BigDecimal(0);
        BigDecimal discount = zero;
        Integer couponId = submitBO.getCouponId();
        Integer userCouponId = submitBO.getUserCouponId();
        if(couponId != null && userCouponId!= null){
            if ( couponId!= 0  &&couponId!=-1 && userCouponId!=-1) {
                MarketCouponUser marketCouponUser = null;
                if(userCouponId == 0) {
                    MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
                    MarketCouponUserExample.Criteria criteriaCU = marketCouponUserExample.createCriteria();
                    criteriaCU.andUserIdEqualTo(userid);
                    criteriaCU.andCouponIdEqualTo(couponId);
                    List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
                     marketCouponUser  = marketCouponUsers.get(0);
                }else {
                     marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(submitBO.getUserCouponId());
                }
                Short status = marketCouponUser.getStatus();
                Boolean deleted = marketCouponUser.getDeleted();
                if (status == 0 && !deleted) {
                    MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(submitBO.getCouponId());
                    discount = marketCoupon.getDiscount();
                }

            }
        }

        System.out.println(discount);
        Optional<BigDecimal> reduce = marketCarts.stream().map(a -> new BigDecimal(a.getNumber()).multiply(a.getPrice())).reduce(BigDecimal::add);
        short size = (short) marketCarts.size();
        BigDecimal goodsPrice = new BigDecimal(0);
        if(reduce.isPresent()){
             goodsPrice = reduce.get();
        }

        //4.创建订单表
        MarketOrder marketOrder = new MarketOrder();
        Date now = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(now);
        int randomId= (int)((Math.random()*9+1)*100000);
        String orderSn = format+ randomId;
        marketOrder.setUserId(userid);
        marketOrder.setOrderSn(orderSn);
        marketOrder.setOrderStatus((short) 101);
        marketOrder.setConsignee(marketAddress.getName());
        marketOrder.setMobile(marketAddress.getTel());
        marketOrder.setAddress(marketAddress.getAddressDetail());
        marketOrder.setMessage(submitBO.getMessage());
        marketOrder.setGoodsPrice(goodsPrice);
        marketOrder.setFreightPrice(zero);
        marketOrder.setCouponPrice(discount);
        marketOrder.setIntegralPrice(zero);
        marketOrder.setGrouponPrice(zero);
        BigDecimal orderPrice = goodsPrice.subtract(discount);
        marketOrder.setOrderPrice(orderPrice);
        marketOrder.setActualPrice(orderPrice);
        marketOrder.setComments(size);
        marketOrder.setAddTime(now);
        marketOrder.setUpdateTime(now);
        int rowC = marketOrderMapper.insertSelective(marketOrder);
        Integer orderId = marketOrder.getId();
        //创建订单商品表
        Integer rows = null;
        if (marketCarts.size() != 0) {
            rows = marketOrderGoodsMapper.insertList(marketCarts, orderId, now);
        }
        if (rows != null && rows > 0) {
            //订单创建之后将用户优惠券删除
            MarketCouponUser marketCouponUser = new MarketCouponUser();
            marketCouponUser.setId(submitBO.getUserCouponId());
            marketCouponUser.setStatus((short)1);
            marketCouponUser.setUsedTime(now);
            marketCouponUser.setOrderId(orderId);
            marketCouponUser.setAddTime(now);
            marketCouponUser.setUpdateTime(now);
            marketCouponUser.setDeleted(true);
            Integer rowA = marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser);
            //订单创建之后将购物车选中的信息删除
            MarketCart marketCart = new MarketCart();
            marketCart.setUpdateTime(now);
            marketCart.setDeleted(true);
            marketCart.setChecked(false);
            MarketCartExample marketCartExample2 = new MarketCartExample();
            MarketCartExample.Criteria criteriaC = marketCartExample2.createCriteria();
            criteriaC.andUserIdEqualTo(userid);
            criteriaC.andCheckedEqualTo(true);
            int rowB = marketCartMapper.updateByExampleSelective(marketCart,marketCartExample2);
        }

        ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
        System.out.println("开始任务");

        //延时1分钟执行系统取消
        service.schedule(new Runnable() {
            @Override
            public void run() {
                MarketOrder marketOrderT = marketOrderMapper.selectByPrimaryKey(orderId);
                Short i = 101;
                if(Objects.equals(marketOrderT.getOrderStatus(), i)){
                    marketOrderT.setOrderStatus((short)103);
                    marketOrderT.setUpdateTime(new Date());
                    int i1 = marketOrderMapper.updateByPrimaryKey(marketOrderT);
                }
            }
        }, 1, TimeUnit.MINUTES);


        return 200;
    }

    @Override
    public Integer prepay(OrderIDBO orderIDBO) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderIDBO.getOrderId());
        Date now = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(now);
        int randomId= (int)((Math.random()*9+1)*100000);
        String payId = format+ randomId;
        marketOrder.setId(orderIDBO.getOrderId());
        marketOrder.setOrderStatus((short) 201);
        marketOrder.setActualPrice(marketOrder.getOrderPrice());
        marketOrder.setPayId(payId);
        marketOrder.setPayTime(now);
        marketOrder.setUpdateTime(now);
        Integer row = marketOrderMapper.updateByPrimaryKey(marketOrder);
        System.out.println("牛逼");
        return row;
    }

    @Override
    public Integer cancel(OrderIDBO orderIDBO) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderIDBO.getOrderId());
        marketOrder.setOrderStatus((short)102);
        marketOrder.setUpdateTime(new Date());
        Integer row = marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        return row;
    }


    private String setStatusText(Short orderStatus) {
        switch (orderStatus) {
            case 101:
                return "未付款";
            case 102:
                return "用户取消";
            case 103:
                return "系统取消";
            case 201:
                return "已付款";
            case 202:
                return "申请退款";
            case 203:
                return "已退款";
            case 301:
                return "已发货";
            case 401:
                return "用户收货";
            case 402:
                return "系统收货";
        }
        return null;
    }

    private WeChatOrderListHandleOption setHandleOption(Short comments, Short orderStatus, Boolean orderDeleted) {
        WeChatOrderListHandleOption weChatOrderListHandleOption = new WeChatOrderListHandleOption();

        switch (orderStatus) {
            case 101:
                weChatOrderListHandleOption.setCancel(true);
                weChatOrderListHandleOption.setPay(true);
                break;
            case 102:
                weChatOrderListHandleOption.setDelete(true);
                break;
            case 103:
                weChatOrderListHandleOption.setDelete(true);
                break;
            case 201:
                weChatOrderListHandleOption.setRefund(true);
                break;
            case 203:
                weChatOrderListHandleOption.setDelete(true);
                break;
            case 301:
                weChatOrderListHandleOption.setRefund(true);
                weChatOrderListHandleOption.setConfirm(true);
                break;
            case 401:
            case 402:
                weChatOrderListHandleOption.setComment(true);
                if (!orderDeleted) {
                    weChatOrderListHandleOption.setDelete(true);
                }
                weChatOrderListHandleOption.setRebuy(true);
                weChatOrderListHandleOption.setAftersale(true);
                break;
        }
        return weChatOrderListHandleOption;
    }
}
